<template>
  <div class="app-container">    
    <el-row :gutter="20">
      <!--分类数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="cateName"
            placeholder="请输入分类名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="cateOptions"
            :props="treeProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="value"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--资产表格数据-->
      <el-col :span="20" :xs="24">

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="型号" prop="model_id">
        <el-select v-model="queryParams.model_id" placeholder="请选择型号" clearable>
          <el-option
              v-for="v in searchModelOptions"
              :key="v.value"
              :label="v.label"
              :value="v.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="仓库" prop="house_id">        
        <el-select v-model="queryParams.house_id" placeholder="请选择仓库" clearable>
          <el-option
            v-for="u in houseOptions"
            :key="u.value"
            :label="u.label"
            :value="u.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="资产编号" prop="num">
        <el-input
          v-model="queryParams.num"
          placeholder="请输入资产编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资产状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择资产状态" clearable>
          <el-option
            v-for="dict in dict.type.assets_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属部门" prop="dept_id">
        <treeselect v-model="queryParams.dept_id" :options="deptOptions" :normalizer="normalizer" placeholder="请选择归属部门" style="width:180px" />
      </el-form-item>
      <el-form-item label="使用人" prop="user_id">
        <el-select v-model="queryParams.user_id" placeholder="请选择使用人" filterable clearable>
          <el-option
            v-for="u in userOptions"
            :key="u.value"
            :label="u.label"
            :value="u.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="购买时间" prop="buy_time">
       <el-date-picker
          v-model="queryParams.buy_time"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['asset:info:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['asset:info:remove']"
        >删除</el-button>
      </el-col>
    <el-col :span="1.5">
    <el-button
        type="info"
        plain
        icon="el-icon-upload2"
        size="mini"
        @click="handleImport"
        v-hasPermi="['asset:warehouse:import']"
    >导入</el-button>
    </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['asset:info:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="资产分类" align="center" prop="cate_name" />
      <el-table-column label="型号" align="center" prop="model_name" />
      <el-table-column label="资产编号" align="center" prop="num" />
      <el-table-column label="当前价值" align="center" prop="price" />
      <el-table-column label="仓库" align="center" prop="house_name" />
      <el-table-column label="图例" align="center" prop="imgs" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.imgs" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="IT设备" align="center" prop="is_it">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.is_it"/>
        </template>
      </el-table-column>
      <el-table-column label="资产状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.assets_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="所属部门" align="center" prop="dept_name" />
      <el-table-column label="使用人" align="center" prop="user_name" />
      <el-table-column label="购买时间" align="center" prop="buy_time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.buy_time, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['asset:info:edit']"
          >修改</el-button>
          <el-button v-if="scope.row.status == '5' || scope.row.status == '6'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['asset:info:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="pager.page"
      :limit.sync="pager.limit"
      @pagination="getList"
    />
     </el-col>
    </el-row>

    <!-- 添加或修改资产信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-tabs v-model="tab">
        <el-tab-pane label="基本信息" name="base">
        <el-form-item label="资产分类" prop="cate_id">
            <treeselect v-model="form.cate_id" :options="cateOptions" :normalizer="normalizer" placeholder="请选择资产分类" />
        </el-form-item>
        <el-form-item label="型号" prop="model_id">
          <el-select v-model="form.model_id" placeholder="请选择型号" clearable>
            <el-option
                v-for="v in formModelOptions"
                :key="v.value"
                :label="v.label"
                :value="v.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="资产编号" prop="num">
          <el-input v-model="form.num" placeholder="请输入资产编号" />
        </el-form-item>
        <el-form-item label="所属部门" prop="dept_id">
            <treeselect v-model="form.dept_id" :options="deptOptions" :normalizer="normalizer" placeholder="请选择所属部门" />
        </el-form-item>
        <el-form-item label="资产状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.assets_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用人" prop="user_id" v-if="form.status == '2'">
        <el-select v-model="form.user_id" placeholder="请选择使用人" filterable clearable>
          <el-option
            v-for="u in userOptions"
            :key="u.value"
            :label="u.label"
            :value="u.value"
          />
        </el-select>
        </el-form-item>
        <el-form-item label="报废时间" prop="scrap_time" v-if="form.status == '5'">
          <el-date-picker clearable
            v-model="form.scrap_time"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择报废时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="仓库" prop="house_id">
          <el-select v-model="form.house_id" placeholder="请选择仓库" clearable>
            <el-option
                v-for="u in houseOptions"
                :key="u.value"
                :label="u.label"
                :value="u.value"
            />
          </el-select>
        </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="详细信息" name="detail">
        <el-form-item label="购买时间" prop="buy_time">
          <el-date-picker clearable
            v-model="form.buy_time"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择购买时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="当前价值" prop="price">
          <el-input v-model="form.price" placeholder="请输入当前价值" />
        </el-form-item>
        <el-form-item label="图例" prop="imgs">
          <image-upload v-model="form.imgs"/>
        </el-form-item>
        <el-form-item label="IT设备" prop="is_it">
          <el-radio-group v-model="form.is_it">
            <el-radio
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上级设备" prop="pid">
          <el-input v-model="form.pid" placeholder="请输入上级设备" />
        </el-form-item>
        <el-form-item label="资产说明" prop="comment">
          <el-input v-model="form.comment" placeholder="请输入资产说明" />
        </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="二维码" name="bar" v-if="form.num">
        <el-form-item prop="qr">
          <template slot="label">
            <el-button type="warning" size="mini" v-print="qrPrinter">打印</el-button>
            <el-button type="info" size="mini" @click="downloadQr">下载</el-button>
            </template>
          <vue-qr id="qrImg" :text="form.num" :margin="0" :logoSrc="qrLogo"
            :callback="qrDataReady" :size="300"></vue-qr>            
        </el-form-item>
        </el-tab-pane>
      </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入 -->
    <import-dialog :open="upload" model="asset_info" @cancel="importCancel" @success="importSuccess" />
  </div>
</template>

<script>
import { apiGet, apiPost, apiPut, apiDelete, apiDs, apiExport, apiDownload } from "@/api/openapi";
import ImportDialog from "@/components/ImportDialog";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import VueQr from 'vue-qr'
import {subTreeIds} from "../tree"

export default {
  name: "Info",
  components: {
    VueQr, Treeselect, ImportDialog
  },
  dicts: ['sys_yes_no', 'assets_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资产信息表格数据
      infoList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      cateName: null,      
      treeProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        cate_id: null,
        model_id: null,
        num: null,
        param1: null,
        param2: null,
        param3: null,
        param4: null,
        param5: null,
        price: null,
        house_id: null,
        imgs: null,
        isIt: null,
        pid: null,
        comment: null,
        status: null,
        dept_id: null,
        user_id: null,
        buy_time: [],
        scrap_time: null,
        "@alias": "t",
        "@exp": {
            num: 'lk',
            cate_id: 'in',
            buy_time:'bt'
        }
      },
      pager: {
        page: 1,
        limit: 10,
        order: "id desc",
      },
      houseOptions: [],
      userOptions: [],
      deptOptions: [],
      cateOptions: [],
      modelOptions: [],
      // 表单参数
      form: {},
      tab: "base",
      upload: false,
      // 表单校验
      rules: {
        cate_id: [
          { required: true, message: "资产分类不能为空", trigger: "blur" }
        ],
        model_id: [
          { required: true, message: "型号不能为空", trigger: "blur" }
        ],
        num: [
          { required: true, message: "资产编号不能为空", trigger: "blur" }
        ],
      },
      qrBackData: null,
      qrLogo: null,
      qrPrinter:{
        id: "qrImg", // 这里是要打印元素的ID
        popTitle: "&nbsp", // 打印的标题
        extraCss: "", // 打印可引入外部的一个 css 文件
        extraHead: "", // 打印头部文字
      }
    };
  },
  created() {
    this.getList();
    apiDs('warehouse_select').then(response=>{
        this.houseOptions = response.data;
    });
    apiDs('user_select').then(response=>{
        this.userOptions = response.data;
    });
    apiDs('dept_select').then(response=>{
        this.deptOptions = this.handleTree(response.data, "value", "parent_id");
    });
    apiDs('asset_model_select').then(response=>{
        this.modelOptions = response.data;
    });
    apiDs('asset_category_select').then(response=>{
        this.cateOptions = this.handleTree(response.data, "value", "pid");
    });
    this.getConfigKey("asset.qr.logo").then(response => {
      this.qrLogo = response.msg;
    });    
  },
  watch: {
    // 根据名称筛选分类树
    cateName(val) {
      this.$refs.tree.filter(val);
    }
  },
  computed: {
    formModelOptions: function () {
      let options = [];
      if(this.form.cate_id == null){
        return options;
      }
      let ids = ',,' + subTreeIds(this.cateOptions, this.form.cate_id)+','

      for(var i=0;i<this.modelOptions.length;i++){
        if(ids.indexOf(','+this.modelOptions[i].cate_id+',')> 0){
          options.push(this.modelOptions[i]);
        }
      }
      return options;
    },    
    searchModelOptions: function () {
      let options = [];
      if(this.queryParams.cate_id == null){
        return options;
      }
      
      let ids = ',,' + subTreeIds(this.cateOptions, this.queryParams.cate_id)+',';

      for(var i=0;i<this.modelOptions.length;i++){
        if(ids.indexOf(','+this.modelOptions[i].cate_id+',')> 0){
          options.push(this.modelOptions[i]);
        }
      }
      return options;
    }
  },
  methods: {
    /** 查询资产信息列表 */
    getList() {
      this.loading = true;
      let params = {};
      params['asset_info'] = {...this.queryParams};
      if(this.queryParams.cate_id){
        params['asset_info']['cate_id'] =  subTreeIds(this.cateOptions, this.queryParams.cate_id);
      }
      if(this.queryParams.buy_time.length == 0){
        params['asset_info']['buy_time'] = null;
      }
      params['@pager'] = this.pager;
      params['asset_model'] = {
          "@alias": "m",
          "@join": "m.id = t.model_id",
          "@column":"name model_name"
      };
      params['asset_category'] = {
          "@alias": "c",
          "@join": "c.id = t.cate_id",
          "@column":"name cate_name"
      };
      params['asset_warehouse'] = {
          "@alias": "h",
          "@join": "h.id = t.house_id",
          "@column":"name house_name"
      };
      params['sys_user'] = {
          "@alias": "u",
          "@join": "LEFT u.user_id = t.user_id",
          "@column":"nick_name user_name"
      };
      params['sys_dept'] = {
          "@alias": "d",
          "@join": "LEFT d.dept_id = t.dept_id",
          "@column":"dept_name"
      };
      apiGet(params).then(response => {
        this.infoList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 转换资产分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.value,
        label: node.label,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        cate_id: this.queryParams.cate_id,
        model_d: null,
        num: null,
        param1: null,
        param2: null,
        param3: null,
        param4: null,
        param5: null,
        price: null,
        houseId: null,
        imgs: null,
        isIt: null,
        pid: null,
        comment: null,
        status: null,
        deptId: null,
        userId: null,
        scrapTime: null
      };
      this.resetForm("form");
      this.tab = 'base';
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(data){
      this.queryParams.cate_id = data.value;
      this.pager.page = 1;
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pager.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加资产信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
        let data = {};
        data['asset_info'] = { id:id};
      apiGet(data).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改资产信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
            let data = {};
            data['asset_info'] = this.form;
            data['@tags'] = ['asset_info'];
          if (this.form.id != null) {
            apiPut(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            apiPost(data).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的资产信息数据？').then(function() {
        let data = {};
        data['asset_info'] = { id:ids, "@exp":{id:"in"}};
        data['@tags'] = ['asset_info'];
        return apiDelete(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload = true;
    },
    importSuccess(msg) {   
        this.upload = false;   
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
    },
    importCancel() {      
        this.upload = false;   
    },
    /** 导出按钮操作 */
    handleExport() {
        let params = {};
      params['asset_info'] = {...this.queryParams};
      if(this.queryParams.cate_id){
        params['asset_info']['cate_id'] =  subTreeIds(this.cateOptions, this.queryParams.cate_id);
      }
      if(this.queryParams.buy_time.length == 0){
        params['asset_info']['buy_time'] = null;
      }
      params['@pager'] = {page:1, limit:1000};
      apiExport(params).then(response => {
        apiDownload(response.msg);
      });
    },
    qrDataReady(data){
        this.qrBackData = data;
    },
    downloadQr() {
        if (window.navigator.msSaveOrOpenBlob) {
        const qrStr= atob(data.split(',')[1]);
        let n = qrStr.length;
        const u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        const blob = new Blob([u8arr]);
        window.navigator.msSaveOrOpenBlob(blob, '资产二维码' + this.form.num+ '.' + 'png');
      } else {
        // 这里就按照chrome等新版浏览器来处理
        const a = document.createElement('a');
        a.href = this.qrBackData;
        a.setAttribute('download', '资产二维码' + this.form.num);
        a.click();
      }
    }
  }
};
</script>
<style>
@page {
    size: auto;
    margin: 0mm;
}
</style>
